

--[[

port ==> tcpport ==> route ==> modules

]]--

require 'playermap'
require 'player'
require 'route'
require 'packet'

local names_map = {}

local function new()
    local fd = UnixSocket.New()
    self =  {
        fd = fd,                                 --unixsocket fd
        playermap = PLAYERMAP.new(),             --player map
        route = ROUTE.new(),
    }


    return self
end

local function connect(self, filename) 
    UnixSocket.Connect(self.fd, filename)
    UnixSocket.OnPacket(self.fd, "TCPPORT.on_packet", self)
end


local function reply(self, linefd, msgid, ...)
    fd = self.fd
    UnixSocket.Send(fd, 100000, linefd, msgid, unpack(arg));
end
local function accept_socket(self, sockfd)
    print("accept is ....");
    UnixSocket.Send(fd, 100002, sockfd);
end



local function dispatch(self, msgid, packet)
    print("dispatch msgid "..msgid) 
    if msgid == 100001 then --新链接
        if ROUTE.dispatch(self.route, msgid, {player=self, packet=packet}) == 0 then --如果没有模块处理,直接accept
            local sockfd = PACKET.read_int(packet)
            accept_socket(self, sockfd)
        end
    elseif msgid == 100006 then --关闭链接
    	linefd = PACKET.read_int(packet)
        player = PLAYERMAP.cget_player(self.playermap, linefd)
        player.tcpport = self;

        ROUTE.dispatch(self.route,   msgid, {player=player, packet=packet})
        ROUTE.dispatch(player.route, msgid, {player=player, packet=packet})
        
        PLAYERMAP.free_player(self.playermap, linefd)
        print("关闭链接");
    elseif msgid == 100000 then --消息转发
        linefd = PACKET.read_int(packet)
        msgid = PACKET.read_int(packet)
        player = PLAYERMAP.cget_player(self.playermap, linefd)

        player.tcpport = self;

        ROUTE.dispatch(self.route,   msgid, {player=player, packet=packet})
        ROUTE.dispatch(player.route, msgid, {player=player, packet=packet})

    else
        linefd = PACKET.read_int(packet)
        player = PLAYERMAP.cget_player(self.playermap, linefd)
        player.tcpport = self;

        ROUTE.dispatch(self.route,   msgid, {player=player, packet=packet})
        ROUTE.dispatch(player.route, msgid, {player=player, packet=packet})
    end
end


local function on_packet(self, fd, msgid, pkt)
    print("on_packet")
    print(self)
    packet = PACKET.new();
    PACKET.set_fd(packet, pkt)
    dispatch(self, msgid, packet);
end



local function rename(self, name)
    names_map[name] = self
end

local function lookup(name)
    return names_map[name]
end

TCPPORT = {
    new = new,
    connect = connect,
    on_packet = on_packet,
    rename = rename,
    lookup = lookup,
    dispatch = dispatch,

    reply = reply,
    
    accept_socket = accept_socket,
    reject_socket = reject_socket,
}
return TCPPORT 



